# -*- coding: utf-8 -*-
import json
import os
import sys

from pypinyin import pinyin, Style

DIST_PATH = "../antankstatic-dist"
JSON_NAME = "{}/img.json".format(DIST_PATH)
# {} 转义需要 {{}}
SYNC_COMM = "rm -fr {} && mkdir -p {} && cp -r `ls . | grep -vE '.git|img_json.py' | xargs` {}".format(DIST_PATH, DIST_PATH, DIST_PATH)
# 文件路径
IMG_PATH = "{}/img/".format(DIST_PATH)


def write_img_json(path: str):
    """
    获取文件名集合，中文转英文首字母，空格用 - 代替，并写入 json 文件
    :param path:
    :return:
    """
    # 同步文件到 antankstatic-dist 并跳转到该目录
    os.system(SYNC_COMM)
    directory = []
    resources = {}
    for file_path, dirs, fs in os.walk(path):
        urls = []
        name_file_path = file_path.replace(IMG_PATH, '')
        for f in fs:
            print(f)
            # 获取文件名首字母简拼并重命名
            file_name = get_file_fl_pinyin_name(f)
            temp_file_name = os.path.join(name_file_path, file_name)
            if file_name != f:
                # 重名重新命名
                if temp_file_name in urls:
                    name, point, suffix = file_name.rpartition('.')
                    file_name = name + '1' + point + suffix
                    temp_file_name = os.path.join(name_file_path, file_name)
                os.rename(os.path.join(file_path, f), os.path.join(file_path, file_name))
            # 目录
            if name_file_path:
                directory.append(name_file_path)
            urls.append(temp_file_name)
        if name_file_path:
            resources[name_file_path] = urls
    directory = distinct_list(directory)
    write_json_file(directory, resources)


def distinct_list(ori_list: list):
    """
    去重后是无序的，重新按照以前的排序
    :param ori_list:
    :return:
    """
    temp_list = list(set(ori_list))
    temp_list.sort(key=ori_list.index)
    return temp_list


def get_file_fl_pinyin_name(file_name: str):
    """
    获取文件首字母简拼名称，空格用 - 代替
    :param file_name:
    :return:
    """
    temp_file_name = ''
    for i in pinyin(file_name, style=Style.FIRST_LETTER):
        temp_file_name += ''.join(i)
    temp_file_name = temp_file_name.replace(' ', '-')
    return temp_file_name


def write_json_file(directory: list, resources: list):
    """
    字典内容写入json
    :param directory:
    :param resources:
    :return:
    """
    json_dict = {
        'directory': directory,
        'resources': resources
    }
    json_str = json.dumps(json_dict, indent=4)
    with open(JSON_NAME, 'w') as json_file:
        json_file.write(json_str)


if __name__ == '__main__':
    write_img_json(IMG_PATH)
